package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.dto.OrderDto;
import com.itheima.reggie.entity.*;
import com.itheima.reggie.mapper.OrdersMapper;
import com.itheima.reggie.service.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * @BelongsProject: java8-reggie
 * @BelongsPackage: com.itheima.reggie.service.impl
 * @Author: lin
 * @CreateTime: 2022-10-24  13:26
 * @Description:
 * @Version: 1.0
 */
@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements OrdersService {

    @Autowired
    OrderDetailService orderDetailService;
    @Autowired
    private UserService userService;
    @Autowired
    private AddressBookService addressBookService;
    @Autowired
    private ShoppingCartService shoppingCartService;

    @Override
    public int submitOrder(Orders orders, HttpSession session) {

        User user = userService.getById((Long) session.getAttribute("user"));
        AddressBook addressBook = addressBookService.getById(orders.getAddressBookId());

        orders.setNumber(UUID.randomUUID().toString().replace("-", ""));
        orders.setStatus(2);
        orders.setUserId((Long) session.getAttribute("user"));
        orders.setOrderTime(LocalDateTime.now());
        orders.setEndTime(LocalDateTime.now());
        orders.setPayMethod(1);
        orders.setPhone(user.getPhone());
        String address = (addressBook.getProvinceName() != null ? addressBook.getProvinceName() : "") +
                (addressBook.getCityName() != null ? addressBook.getCityName() : "") +
                (addressBook.getDistrictName() != null ? addressBook.getDistrictName() : "") +
                (addressBook.getDetail() != null ? addressBook.getDetail() : "");

        orders.setAddress(address);
        orders.setUserName(user.getName());
        orders.setConsignee(addressBook.getConsignee());

        boolean result1 = this.save(orders);
        LambdaQueryWrapper<ShoppingCart> lqw = new LambdaQueryWrapper<>();
        lqw.eq(ShoppingCart::getUserId, (Long) session.getAttribute("user"));
        List<ShoppingCart> cartList = shoppingCartService.list(lqw);

        List<OrderDetail> detailList = cartList.stream().map(shoppingCart -> {

            OrderDetail orderDetail = new OrderDetail();

            BeanUtils.copyProperties(shoppingCart, orderDetail);

            orderDetail.setOrderId(orders.getId());

            return orderDetail;
        }).collect(Collectors.toList());

        boolean result2 = orderDetailService.saveBatch(detailList);
        if (result1 && result2) {

            shoppingCartService.remove(lqw);

            return 1;
        }

        return 0;
    }

    @Override
    public IPage<OrderDto> pageAll(PageParam pageParam) {
        LambdaQueryWrapper<Orders> lqw = new LambdaQueryWrapper<>();
        lqw.like(pageParam.getNumber() != null, Orders::getNumber, pageParam.getNumber());
        lqw.between(pageParam.getBeginTime() != null, Orders::getOrderTime, pageParam.getBeginTime(), pageParam.getEndTime());
        IPage<Orders> ip = new Page<>(pageParam.getPage(), pageParam.getPageSize());
        IPage<Orders> op = getBaseMapper().selectPage(ip, lqw);
        IPage<OrderDto> page = new Page<>();
        page.setTotal(op.getTotal());
        List<OrderDto> collect = op.getRecords().stream().map(rec -> {
            OrderDto orderDto = new OrderDto();
            BeanUtils.copyProperties(rec, orderDto);
            orderDto.setUserName(userService.getById(rec.getUserId()).getName());
            LambdaQueryWrapper<OrderDetail> lq = new LambdaQueryWrapper<>();
            lq.eq(OrderDetail::getOrderId, rec.getId());
            orderDto.setOrderDetails(orderDetailService.list(lq));
            return orderDto;
        }).collect(Collectors.toList());
        page.setRecords(collect);
        return page;
    }
}
